package sc.core.model.auth;

import java.util.ArrayList;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;

import sc.core.auth.enums.PermissionEnum;
import sc.core.dal.dataobject.UserInfoDO;

public class UserToken implements UserDetails {

	private static final long serialVersionUID = 6911029184925374875L;

	public UserToken(UserInfoDO userInfoDO) {
		super();
		this.userInfoDO = userInfoDO;
		for (PermissionEnum p : userInfoDO.getPermissions()) {
			grantedAuthList.add(new GrantedAuthorityImpl(p.toString()));
		}
	}

	UserInfoDO userInfoDO;
	ArrayList<GrantedAuthority> grantedAuthList = new ArrayList<GrantedAuthority>();

	@Override
	public GrantedAuthority[] getAuthorities() {
		if (grantedAuthList == null || grantedAuthList.isEmpty())
			return new GrantedAuthority[0];
		return grantedAuthList.toArray(new GrantedAuthority[0]);
	}

	@Override
	public String getPassword() {
		return (userInfoDO != null && userInfoDO.getUserLoginDO() != null) ? userInfoDO
				.getUserLoginDO().getPassword() : null;
	}

	@Override
	public String getUsername() {
		return (userInfoDO != null && userInfoDO.getUserLoginDO() != null) ? userInfoDO
				.getUserName() : null;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public UserInfoDO getUserDO() {
		return userInfoDO;
	}

	public void setUserDO(UserInfoDO userDO) {
		this.userInfoDO = userDO;
	}

	public ArrayList<GrantedAuthority> getGrantedAuthList() {
		return grantedAuthList;
	}

	public void setGrantedAuthList(ArrayList<GrantedAuthority> grantedAuthList) {
		this.grantedAuthList = grantedAuthList;
	}
}
